package sortStudy;

import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;

public class FrequencySort {

    public String frequencySort(String s) {
        if (s == null || s.length() <= 0){
            return s;
        }
        HashMap<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < s.length(); i++){
            map.put(s.charAt(i), map.getOrDefault(s.charAt(i), 0) + 1);
        }
        //创建优先队列，进行从小到大排序
        PriorityQueue<CountEntry> queue = new PriorityQueue<>(((o1, o2) -> {
            return o2.value - o1.value;
        }));
        for (Map.Entry<Character, Integer> entry : map.entrySet()) {
            Character key = entry.getKey();
            Integer value = entry.getValue();
            queue.offer(new CountEntry(key, value));
        }
        StringBuilder sb = new StringBuilder();
        while (!queue.isEmpty()){
            CountEntry c = queue.poll();
            for (int j = 1; j <= c.value; j++){
                sb.append(c.key);
            }
        }
        return sb.toString();
    }
}
class CountEntry{
    public Character key;
    public Integer value;
    public CountEntry(Character key, Integer value){
        this.key = key;
        this.value = value;
    }
}
